<script>
import {Message} from "@element-plus/icons-vue";
import CryptoJS from "crypto-js";
import request from "../../utils/Request.js";
import {ElMessage, ElNotification} from "element-plus";
import store from "../../store/index.js";

export default {
  name: "BindingCard",
  components: {Message},
  data() {
    return {
      dialogFormVisible: false,
      countDownValue: 0,
      isCountDown: false,
      disableCodeButton: false,
      disableBindingButton: false,
      form: {
        email: '',
        password: '',
        passwordConfirm: '',
        code: ''
      },
      rules: {
        email: [
          {required: true, message: '请输入邮箱地址', trigger: 'change'},
          {type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur'},
        ],
        code: [
          {required: true, message: '请输入验证码', trigger: 'change'},
          {type: 'number', message: '请输入正确的验证码', trigger: 'blur'},
        ],
        password: [{
          validator: (rule, value, callback) => {
            if (value === '')
              callback(new Error('请输入密码'))
            else if (!new RegExp("^[a-zA-Z0-9]{6,18}$").test(value))
              callback(new Error('请输入6到18位的不包括特殊字符的密码'))
            else
              callback()
          }, trigger: 'blur'
        }],
        passwordConfirm: [{
          validator: (rule, value, callback) => {
            if (value === '')
              callback(new Error('请再一次输入密码'))
            else if (value !== this.form.password)
              callback(new Error('两次输入的密码不一致'))
            else
              callback()
          }, trigger: 'blur'
        }]
      }
    }
  },
  methods: {
    sendCode() {
      let form = this.$refs['form']
      form.validateField('email', (valid) => {
        if (valid) {
          if (!this.isCountDown) {
            this.disableCodeButton = true
            // 发送验证码
            // 邮箱Base64编码
            let emailEncoded = CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse(this.form.email))
            // console.log(CryptoJS.enc.Utf8.stringify(CryptoJS.enc.Base64.parse(emailEncoded)))
            request({
              method: 'post',
              url: '/api/uaa/user/binding/code?email=' + emailEncoded,
            })
                .then(resp => {
                  let data = resp.data
                  if (data.code === 0) {
                    // 发送成功
                    ElMessage.success("发送验证码成功！")
                    this.isCountDown = true;
                    this.countDownValue = Date.now() + 60000
                  } else if (data.code === 1204) {
                    ElMessage.error('请勿频繁发送验证码！')
                    this.isCountDown = true;
                    this.countDownValue = Date.now() + 60000
                  } else {
                    ElMessage.error(data.msg)
                  }
                  this.disableCodeButton = false
                })
                .catch(err => {
                  console.log(err)
                  if (!this.isCountDown)
                    ElMessage.error('发送验证码失败！')
                  this.disableCodeButton = false
                })

          } else {
            ElMessage.error('请勿频繁发送验证码！')
          }
        }
      })
    },
    binding() {
      let form = this.$refs['form']
      form.validate((valid) => {
        if (valid) {
          this.disableBindingButton = true
          //  注册
          request({
            method: 'post',
            url: '/api/uaa/user/binding',
            data: {
              email: this.form.email,
              password: CryptoJS.SHA256(this.form.password).toString(CryptoJS.enc.Hex),
              code: this.form.code
            }
          })
              .then(resp => {
                if (resp.data.code === 0) {
                  ElMessage.success('绑定成功！')
                  this.dialogFormVisible = false
                } else if (resp.data.code === 1302) {
                  ElMessage.error("验证码错误")
                } else {
                  ElMessage.error(resp.data.msg)
                }
                this.disableBindingButton = false
              })
              .catch(err => {
                console.log(err)
                ElMessage.error("出现未知错误！")
                this.disableBindingButton = false
              })
        } else {
          ElMessage.error('请检查是否填写完整')
        }
      })
    },
    unbinding(type) {
      if (this.countBinding === 1) {
        ElMessage.error("最少需要留一个绑定关系!")
        return;
      }

      console.log(type)

      request({
        method: 'post',
        url: '/api/uaa/user/unbinding/' + type
      })
          .then(resp => {
            if (resp.data.code === 0) {
              ElMessage.success('解绑成功！')
            } else {
              ElMessage.error(resp.data.msg)
            }
          })
          .catch(err => {
            console.log(err)
            ElMessage.error("出现未知错误！")
          })
    }, // end unbinding()
    bindingOAuth2(regId) {
      request({
        method: 'get',
        url: '/api/uaa/oauth2/authorization/' + regId
      })
          .then(({data}) => {
            if (data.code === 0) {
              window.location.href = data.data
            } else {
              ElMessage.error(data.msg)
            }
          })
          .catch(err => {
            console.log(err)
            ElMessage.error("出现未知错误！")
          })
    }
  },
  computed: {
    countBinding() {
      return (store.state.user.giteeId != null) + (store.state.user.githubId != null) + (store.state.user.email != null)
    }
  }
}
</script>

<template>

  <el-dialog v-model="dialogFormVisible" title="绑定邮箱" :modal="false" :close-on-click-modal="false" top="0">
    <el-form :model="form" :rules="rules" ref="form">
      <el-form-item prop="email" key="email">
        <el-input class="w-300 mb-5" size="small" v-model="form.email" placeholder="邮箱" clearable
                  maxlength="64"/>
      </el-form-item>
      <el-form-item prop="password" key="password">
        <el-input class="w-300 mb-5" size="small" v-model="form.password" placeholder="设置账号密码" type="password"
                  show-password
                  clearable maxlength="20"/>
      </el-form-item>
      <el-form-item prop="passwordConfirm" key="passwordConfirm">
        <el-input class="w-300 mb-5" size="small" v-model="form.passwordConfirm" placeholder="再次输入密码"
                  type="password"
                  show-password
                  clearable maxlength="20"/>
      </el-form-item>
      <el-form-item prop="code" key="code">
        <el-input class="w-300 mb-5" size="small" v-model.number="form.code" placeholder="验证码"
                  type="number"
                  maxlength="6">
          <template #append>
            <el-button @click="sendCode" :disabled="disableCodeButton || isCountDown">
              <span v-show="!isCountDown">
              发送
              </span>
              <el-countdown
                  v-show="isCountDown"
                  format="ss"
                  :value="countDownValue"
                  @finish="this.isCountDown = false"
                  class="w-50"
                  :value-style="{ fontSize: '17px', color: 'gray' }"
              />
            </el-button>
          </template>
        </el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="dialogFormVisible = false">取消</el-button>
      <el-button type="primary" @click="binding()" :disabled="disableBindingButton">
        绑定
      </el-button>
    </template>
  </el-dialog>

  <el-card>
    <el-text style="font-weight: bold">账号绑定</el-text>
    <el-divider/>
    <el-row :gutter="5">
      <el-col :span="5">
        <Message class="w-50"/>
      </el-col>
      <el-col :span="14">
        <el-text>
          {{ this.$store.state.user.email == null ? '快来绑定邮箱吧！' : this.$store.state.user.email }}
        </el-text>
      </el-col>
      <el-col :span="5">
        <el-button type="primary" v-if="this.$store.state.user.email == null" plain
                   @click="dialogFormVisible = true"
        >绑定
        </el-button>
        <el-popconfirm title="确定解绑邮箱？" v-else @confirm="unbinding('email')">
          <template #reference>
            <el-button type="danger" plain>解绑</el-button>
          </template>
        </el-popconfirm>
      </el-col>
    </el-row>
    <el-divider/>
    <el-row :gutter="5">
      <el-col :span="5">
        <el-image src="/logo_github.svg" style="width: 50px; height: 50px"/>
      </el-col>
      <el-col :span="14">
        <el-text v-if="this.$store.state.user.githubId == null">
          快来绑定Github吧！
        </el-text>
        <el-link v-else :href="'https://github.com/' + this.$store.state.user.githubName">
          {{ this.$store.state.user.githubName }}
        </el-link>
      </el-col>
      <el-col :span="5">
        <el-button type="primary" v-if="this.$store.state.user.githubId == null" plain @click="bindingOAuth2('github')">
          绑定
        </el-button>
        <el-popconfirm title="确定解绑Github？" v-else @confirm="unbinding('github')">
          <template #reference>
            <el-button type="danger" plain>解绑</el-button>
          </template>
        </el-popconfirm>
      </el-col>
    </el-row>
    <el-divider/>
    <el-row :gutter="5">
      <el-col :span="5">
        <el-image src="/logo_gitee.svg" style="width: 50px; height: 50px"/>
      </el-col>
      <el-col :span="14">
        <el-text v-if="this.$store.state.user.giteeId == null">
          快来绑定Gitee吧！
        </el-text>
        <el-link v-else :href="'https://gitee.com/' + this.$store.state.user.giteeName">
          {{ this.$store.state.user.giteeName }}
        </el-link>
      </el-col>
      <el-col :span="5">
        <el-button type="primary" v-if="this.$store.state.user.giteeId == null" plain @click="bindingOAuth2('gitee')">
          绑定
        </el-button>
        <el-popconfirm title="确定解绑Gitee？" v-else @confirm="unbinding('gitee')">
          <template #reference>
            <el-button type="danger" plain>解绑</el-button>
          </template>
        </el-popconfirm>
      </el-col>
    </el-row>
    <el-divider/>
  </el-card>
</template>

<style scoped>

</style>